package com.alibaba.springboot.health.controller;

import com.alibaba.springboot.health.pojo.User;
import com.alibaba.springboot.health.pojo.UserRole;
import com.alibaba.springboot.health.service.UserRoleService;
import com.alibaba.springboot.health.service.UserService;
import com.alibaba.springboot.health.vo.UserVo;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2019-12-24 14:33:36
 */
@Controller
public class UserController {

    private static final Logger LOGGER = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 通过用户名登陆
     *
     * @param user 用户名
     * @return 单条数据
     */
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public String login(User user, HttpSession session, Model model) {
        session.removeAttribute("msgadmin");
        try {
            //1.认证
            //2.创建令牌
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());

            //3.获取主体对象
            Subject subject = SecurityUtils.getSubject();
            //4.登陆方法
            subject.login(token);

            if (subject.isAuthenticated()) {
                LOGGER.info("认证成功");
                User user1 = userService.queryByName(user.getUserName());
                if (user1.getStatus() == 0) {
                    session.setAttribute("user", user1);
                    if (subject.hasRole("user")) {
                        LOGGER.info("=========user111111111111111=======");
                        return "index";
                    }
                } else {
                    session.setAttribute("msguser", "当前用户被冻结，请联系管理员");
                    return "redirect:/error";
                }
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            LOGGER.error("认证失败");
        }
        session.setAttribute("msguser", "用户名或密码错误");
        return "redirect:/error";
    }


    /**
     * 通过用户名登陆
     *
     * @param user 用户名
     * @return 单条数据
     */
    @RequestMapping(value = "/user/adlogin", method = RequestMethod.POST)
    public String adlogin(User user, HttpSession session, Model model) {
        session.removeAttribute("msguser");
        try {
            //1.认证
            //2.创建令牌
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());

            //3.获取主体对象
            Subject subject = SecurityUtils.getSubject();

            //4.登陆方法
            subject.login(token);
            if (subject.isAuthenticated()) {
                LOGGER.info("认证成功");
                User user1 = userService.queryByName(user.getUserName());
                if (user1.getStatus() == 0) {
                    session.setAttribute("user", user1);
                    if (!subject.hasRole("admin")) {
                        LOGGER.info("===admin==2222222222222===========");
                        return "main";
                    }
                } else {
                    session.setAttribute("msgadmin", "当前用户被冻结，请联系管理员");
                    return "redirect:/unauth";
                }
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            LOGGER.error("认证失败");
        }
        session.setAttribute("msgadmin", "用户名或密码错误");
        return "redirect:/error";
    }

    /**
     * 安全退出
     * @param session
     * @return
     */
    @RequestMapping(value = "/user/outLogin", method = RequestMethod.GET)
    public String outLogin(HttpSession session) {
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            session.removeAttribute("user");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }

    @RequestMapping(value = "/user/reg", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<UserVo> reg(UserVo user) {

        User queryByName = userService.queryByName(user.getUserName());
        LOGGER.info(queryByName + "==============");

        if (queryByName == null) {

            UserVo user1 = userService.insert(user);
            UserRole userRole = new UserRole();
            userRole.setRoleId(2);
            userRole.setUserId(user1.getUserId());
            UserRole userRole1 = userRoleService.insert(userRole);
            LOGGER.info("133333333333333333333" + userRole1);
            return new ResponseEntity(user1, HttpStatus.OK);
        }

        return new ResponseEntity(HttpStatus.BAD_REQUEST);

    }

    /**
     * zdj
     *
     * @param user
     * @return
     */
    @RequestMapping("/user/update")
    @ResponseBody
    public User update(User user) {
        System.out.println(user + "==========================================");
        User update = userService.update(user);
        return update;
    }

    /**
     * zdj
     * <p>
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("/user/searchOne")
    public String searchOne(Integer id, Model model) {
        User user = userService.queryById(id);
        model.addAttribute("user", user);
        System.out.println("======================================================" + id);
        return "member-edit";
    }

    /**
     * zdj
     * 权限  后台用户  admin
     * 查询多条数据
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param user     实体
     * @return PageInfo<User> 分页数据集合
     */
    @RequiresPermissions(value = {"/user/searchAll"})
    @RequestMapping("/user/searchAll")
    public String searchAll(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize, User user, Model model) {
        PageInfo<User> users = userService.queryAll(page, pageSize, user);
        LOGGER.info("===========================================================" + users);
        model.addAttribute("users", users);
        return "member-list";
    }

}